package web.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import utils.Utils;

import main.TankSicherheit;

/**
 * Servlet implementation class UserLogin
 */
public class UserLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private RequestDispatcher jsp;

       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserLogin() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    @Override
    public void init(ServletConfig config)
    {
    	ServletContext context = config.getServletContext();
		jsp = context.getRequestDispatcher("/WEB-INF/jsp/userlogin.jsp");
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		jsp.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		TankSicherheit.LOGGER.debug("UserLoginServlet");
		String pw = request.getParameter("password");
		String username = request.getParameter("username");

		TankSicherheit.LOGGER.debug("user "+username+" attempts to login");
		int userid = TankSicherheit.staticUserloginByNameAndPw(username, pw);
		if(userid>=0)
		{
			HttpSession session = request.getSession();
			session.setAttribute("USERID", userid);
			response.sendRedirect("home");
			TankSicherheit.LOGGER.debug("user "+username+" logged in successful");
		}
		else
		{
			request.setAttribute("message", "bad username or pw");
			TankSicherheit.LOGGER.debug("user "+username+" failed to login");
		}
	}

}
